﻿#include "computerwindget.h"
#include "ui_computerwindget.h"
#include "computermanager.h"
#include <QMessageBox>

ComputerWindget::ComputerWindget(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ComputerWindget)
{
    ui->setupUi(this);
    this->setMaximumSize(402,344);
    this->setMinimumSize(402,344);
}

ComputerWindget::~ComputerWindget()
{
    delete ui;
}

void ComputerWindget::prepareCreate()
{
    ui->delButton->hide();
    computer.fromSource = ComputerFromSource_addByManual;
    this->setWindowTitle("新增");

}

void ComputerWindget::prepareUpdate(Computer& computer)
{
    this->computer = computer;
    this-> setWindowTitle("更新");
    ui->nameLineEdite->setText(computer.name);
    ui->ipLineEdit->setText(computer.ip);
    ui->commentTextEdit->setText(computer.comment);
}

void ComputerWindget::on_cancelButton_clicked(bool checked)
{
    this->close();
}

void ComputerWindget::on_saveButton_clicked(bool checked)
{
    if(ui->nameLineEdite->text().length() <= 0)
    {
        QMessageBox::information(this, "提示", "名称不能为空");
        return;
    }

    if(ui->ipLineEdit->text().length() <= 0)
    {
        QMessageBox::information(this, "提示", "设置不能为空");
        return;
    }

    computer.name = ui->nameLineEdite->text();
    computer.ip = ui->ipLineEdit->text();
    computer.comment = ui->commentTextEdit->toPlainText();

    if(f_success == gComputerManager.saveOneComputer(computer))
    {
        QMessageBox::information(this,"提示", "保存服务器成功");
        this->close();
    }
    else
    {
        QMessageBox::information(this,"提示", "保存服务器失败");
    }


}

void ComputerWindget::on_delButton_clicked(bool checked)
{
    if(QMessageBox::Yes == QMessageBox::information(this, "提示", "确认要删除该服务器以及所有异常日志吗？",QMessageBox::Yes | QMessageBox::No))
    {
        gComputerManager.deleteOneComputer(computer.id);
        close();
    }
}

void ComputerWindget::on_ipLineEdit_editingFinished()
{
    QString ip = ui->ipLineEdit->text();
    if(ip.length() > 0)
    {
        Computer temp;
        if(f_success == gComputerManager.getOneComputerByIP(ip.toStdString(), temp))
        {
            if(temp.id != computer.id)
            {
                QMessageBox::warning(this, "提示","ip地址已经存在，请重新输入");
                ui->ipLineEdit->setText("");
                ui->ipLineEdit->setFocus();
            }
        }
    }
}
